import { defineStore } from "pinia";
import WebsocketClient from "@/utils/WebsocketClient.js";
import {getToken,getUser} from "@/utils/auth"
import useUserStore from "@/store/modules/user";

const useWebsocketStore = defineStore("ws",{
    state:()=>{
        return {
            ws:null,//websocket的链接状态
            line_msg:"正在连接中...."
        }
    },
    actions:{
        //获取当前登录的用户的基本信息，把用户上线
        online(){
            //获取当前登录用户的信息
            if(!getToken() || !getUser()){
                console.error("用户未登录无法连接ws");
                return ;
            }

            //执行连接socket的操作
            const user = useUserStore().user;
            const websocket_host = import.meta.env.VITE_APP_WEBSOCKT_HOST;
            console.log(websocket_host);

            this.ws = new WebsocketClient({url:`${websocket_host}chat/${user.username}`});
        }
    }
})

export default useWebsocketStore;